import random
from datetime import datetime
from flask import Flask, request
from flask_socketio import SocketIO, emit, rooms

app = Flask(__name__)
socket = SocketIO(app)

users = []  # 所有用户
bind_list=[]    #绑定关系
used_ids = []  # 已使用过的ID,在线用户的ID
pd_bind=False


#   生成ID
def make_ids():
    global used_ids, users
    while True:
        user_id = str(random.randint(100000, 999999))
        if user_id not in used_ids:
            used_ids.append(user_id)
            return user_id


#   创建用户
def make_user(sid, ip_addr):
    global used_ids, users
    user = {
        "sid": sid,
        "id": make_ids(),
        "ip": ip_addr,
        "time": str(datetime.now())[:-7]
    }
    users.append(user)
    return user


@app.route('/')
def index():
    return "欢迎使用通信系统"


@socket.on('connect')
def connect():
    sid = request.sid
    ip_addr=request.remote_addr
    user = make_user(sid,ip_addr)
    print(user)
    emit("my_response", user)


@socket.on('disconnect')
def disconnect():
    global used_ids, users
    sid = request.sid
    for user in users:
        if user["sid"] == sid:
            used_ids.remove(user["id"])


@socket.on('pd_bind')
def pd_bind_status(data):
    global pd_bind
    if data["bind"]==0:
        pd_bind=True
    else:
        pd_bind=False

# 绑定用户
@socket.on('bind_u')
def bind_u(data):
    global bind_list,used_ids,pd_bind
    print("收到绑定信息:", data)
    send_obj=data["my_id"]
    accept_obj=data["accept_id"]
    if accept_obj in used_ids:
        emit("accepting_bind",{
            "bind_id":send_obj,
            "msg":f"{send_obj}向你发送了绑定请求，要同意吗？（yes/no)"
        })
        if pd_bind:
            bind_obj = {
                "bind_A": send_obj,
                "bind_B": accept_obj
            }
            bind_list.append(bind_obj)
            emit("bind_status", {"status": 0, "bind_data": bind_obj, "msg": "绑定成功"})
            pd_bind=False
        else:
            emit("bind_status", {"status": -1, "bind_data": "","msg": "啊哦，对方拒绝了你的绑定"})

    else:
        emit("bind_status",{"status":-1,"bind_data":{},"msg":"绑定失败，该用户不在线或不存在"})

# 发送信息
@socket.on('send_msg')
def send_msg(data):
    send_obj=data["my_id"]
    msg=data["msg"]
    stime=data["stime"]
    accept_obj=[i["bind_B"] for i in bind_list if i["bind_A"]==send_obj]
    accept_sid=[i["sid"] for i in users if i["id"]==accept_obj[0]]
    send_data={"send_obj":send_obj,"msg":msg,"stime":stime}
    print(send_data)
    emit("receive",send_data,room=accept_sid)



if __name__ == '__main__':
    socket.run(app, debug=True, host='0.0.0.0')
